#Tools for generating charts

from collections import namedtuple
from mako.template import Template
import json

ASIAN_COLOR = '#0093BB'
BLACK_COLOR = '#93B216'
HISPANIC_COLOR = '#F5D600'
NATIVEAMERICAN_COLOR = '#E8970A'
WHITE_COLOR = '#683B1A'

COLOR_LIST = [ASIAN_COLOR, BLACK_COLOR, HISPANIC_COLOR, NATIVEAMERICAN_COLOR, WHITE_COLOR]

RaceTuple = namedtuple('RaceTuple', 'name value color')

def get_race_list(asian=0, black=0, hispanic=0, nativeamerican=0, white=0):
    race_list = []
    race_list.append(RaceTuple(name='Asian', value=asian, color=ASIAN_COLOR))
    race_list.append(RaceTuple(name='Black', value=black, color=BLACK_COLOR))
    race_list.append(RaceTuple(name='Hispanic', value=hispanic, color=HISPANIC_COLOR))
    race_list.append(RaceTuple(name='Native American', value=nativeamerican, color=NATIVEAMERICAN_COLOR))
    race_list.append(RaceTuple(name='White', value=white, color=WHITE_COLOR))

    return race_list

def get_race_list_no_zeros(**kwargs):
    race_list = get_race_list(**kwargs)

    return [x for x in race_list if x.value > 0]


class RacePieChart(object):
    
    def __init__(self, **kwargs):
        self.race_list = get_race_list_no_zeros(**kwargs)
        

    def get_data(self):
        row = 0
        data = []
        for race_tuple in self.race_list:
            data.append("""data.setValue(%s, 0, '%s');""" % (row, race_tuple.name))
            data.append("""data.setValue(%s, 1, %s);""" % (row, race_tuple.value))
            row+=1

        return row+1, "\n".join(data)


    def get_colors(self):
        """
        Return the color list, something like:
        
        '#0093BB', '#93B216', '#F5D600', '#E8970A', '#683B1A'
        """
        
        colors = []
        for race_tuple in self.race_list:
            colors.append("'%s'" % race_tuple.color)
        return ", ".join(colors)

        

    def get_js(self, div):
        count, data = self.get_data()
        return """
        // Set a callback to run when the Google Visualization API is loaded.
        google.setOnLoadCallback(drawPieChart);
  
        function drawPieChart() {
          // Create and populate the data table.
          var data = new google.visualization.DataTable();
          data.addColumn('string', 'Race');
          data.addColumn('number', 'Total Per Year');
          data.addRows(%(datacount)s);

          %(data)s

         // Create and draw the visualization.
         var chart = new google.visualization.PieChart(document.getElementById('%(div)s'));
         chart.draw(data, {width: 400, 
                           height: 240, 
                           is3D: false,
                           colors:[%(colorlist)s]});
       }""" % {'colorlist': self.get_colors(),
               'datacount': count,
               'data': data,
               'div': div}


          
          
class YearOverYearChart(object):
    template = """\
    google.setOnLoadCallback(drawYearOverYearChart);
        
    function drawYearOverYearChart() {
      // Create and populate the data table.
      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Year');
      data.addColumn('number', 'Asian');
      data.addColumn('number', 'Black');
      data.addColumn('number', 'Hispanic');
      data.addColumn('number', 'Native American');      
      data.addColumn('number', 'White');  
      data.addRows(${len(years)});

      <% i = 0 %>
      % for year in years:
      data.setCell(${i}, 0, '${year.year}');
      <% i+=1 %>
      % endfor

      <% i = 0 %>
      % for year in years:  
      data.setCell(${i}, 1, ${year.asian});
      data.setCell(${i}, 2, ${year.black});
      data.setCell(${i}, 3, ${year.hispanic});
      data.setCell(${i}, 4, ${year.nativeamerican});      
      data.setCell(${i}, 5, ${year.white});
      <% i+=1 %>
      % endfor

      // Create and draw the visualization.
      new google.visualization.LineChart(document.getElementById('yearbyyear')).draw(data, {'colors': ${colors}});
    }"""

    def __init__(self, years):
        self.years = years

    def get_js(self):
        template = Template(self.template)
        return template.render(years = self.years,
                               colors = json.dumps(COLOR_LIST))

